<template>
  <el-dialog
    :append-to-body="true"
    :visible.sync="dialog"
    :title="isAdd ? '新增' : '编辑'"
    width="680px"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      :inline="true"
      size="small"
      label-width="100px"
    >
      <!-- <el-form-item label="所属系统" > -->
      <!-- <el-input v-model="form.eqptsystem" style="width: 200px;"/> -->
      <!-- </el-form-item> -->
      <el-form-item label="所属系统" prop="eqptsystem">
        <el-select
          v-model="form.eqptsystem"
          :style="style"
          placeholder="请先选择所属系统"
          @change="selectFun"
        >
          <el-option
            v-for="(item, index) in eqptSystemList"
            :key="item.label + index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="设备类型" > -->
      <!-- <el-input v-model="form.eqpttypeid" style="width: 200px;"/> -->
      <!-- </el-form-item> -->
      <el-form-item label="设备类型" prop="eqpttypeid">
        <el-select v-model="form.eqpttypeid" :style="style" placeholder="请先选择设备类型">
          <el-option
            v-for="(item, index) in eqptTypeList"
            :key="item.name + index"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备编号">
        <el-input v-model="form.eqptcode" style="width: 200px;" />
      </el-form-item>
      <el-form-item label="设备序列号" prop="serialno">
        <el-input v-model="form.serialno" style="width: 200px;" />
      </el-form-item>

      <el-form-item label="客户名称" prop="customerName">
        <el-autocomplete
        style="width: 450px"
        class="inline-input"
        v-model="form.customerName"
        :fetch-suggestions="querySearch"
        :trigger-on-focus="false" 
        @select="handleSelect"/>
      </el-form-item>

      <!-- <el-form-item label="品牌" >
        <el-input v-model="form.brandname" style="width: 200px;"/>
      </el-form-item>-->
      <el-form-item label="品牌">
        <el-select
          allow-create
          filterable
          @keyup.enter.native="onSubmitBrand"
          default-first-option
          v-model="form.brandname"
          :style="style"
          placeholder="请先选择品牌"
        >
          <el-option
            v-for="(item, index) in eqptbrandlist"
            :key="item.label + index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="型号" >
        <el-input v-model="form.modelname" style="width: 200px;"/>
      </el-form-item>-->
      <el-form-item label="型号">
        <el-select
          allow-create
          filterable
          @keyup.enter.native="onSubmitModelname"
          default-first-option
          v-model="form.modelname"
          :style="style"
          placeholder="请先选择型号"
        >
          <el-option
            v-for="(item, index) in eqptmodelnamelist"
            :key="item.label + index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="资产负责人">
        <el-input v-model="form.header" style="width: 200px;" />
      </el-form-item>
      <el-form-item label="负责人电话">
        <el-input v-model="form.headerphone" style="width: 200px;" />
      </el-form-item>
      <el-form-item label="生产厂家">
        <el-input v-model="form.manufacturer" style="width: 200px;" />
      </el-form-item>
      <el-form-item label="购置时间" >
        <!-- <el-input v-model="form.purtime" style="width: 370px;" /> -->
        <el-date-picker
            v-model="form.purtime"
            type="datetime"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 200px"
            placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="供应商">
        <el-input v-model="form.supplier" style="width: 200px;" />
      </el-form-item>
      <el-form-item label="供应商联系人">
        <el-input v-model="form.suppliercontact" style="width: 200px;" />
      </el-form-item>
      <el-form-item label="联系人电话">
        <el-input v-model="form.suppliercontactphone" style="width: 200px;" />
      </el-form-item>
      <el-form-item label="质保期限" prop="warrantytime">
        <el-input v-model="form.warrantytime" style="width: 200px;" />
      </el-form-item>
      <el-form-item label="设备名称" >
        <el-input v-model="form.eqptname" style="width: 515px;" />
      </el-form-item>
      <el-form-item label="安装位置" prop="location">
        <el-input v-model="form.location" style="width: 515px;" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.eqptdesc" style="width: 515px;" />
      </el-form-item>
      <!-- <el-form-item label="设备状态" > -->
      <!-- <el-input v-model="form.eqptstate" style="width: 200px;"/> -->
      <!-- </el-form-item> -->
      <el-form-item label="设备状态">
        <el-select v-model="form.eqptstate" :style="style" placeholder="请先选择设备状态">
          <el-option
            v-for="(item, index) in eqptstatelist"
            :key="item.label + index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
       
    </el-form>
    <el-upload
      style="display: inline"
      :show-file-list="false"
      :on-success="onSuccess"
      :on-error="onError"
      :before-upload="beforeUpload"
      :headers="headers"
      list-type="picture"
      :action="uploadUrl()">
      <el-button size="mini" type="success" :disabled="!enabledUploadBtn"><i class="el-icon-plus"/></el-button>
    </el-upload>
    <el-table :data="fileList" style="width: 100%">
      <el-table-column align="center" label="序号">
        <template slot-scope="scope">
          <span v-text="scope.$index + 1"></span>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="文件名">
        <template slot-scope="scope">
          <a
            class="download"
            target="_blank"
            :href="download(scope.row.attatchname)"
            title="下载"
          >{{scope.row.attatchname}}</a>
        </template>
      </el-table-column>

      <el-table-column>
          <template slot-scope="scope">
            <img width="40" height="40" @error="handleLoadError" id="scope.filename"/>
          </template>
      </el-table-column>

      <!-- <el-table-column
        prop="size"
        label="文件大小">
      </el-table-column>-->
      <el-table-column align="center" label="管理" width="220">
        <template slot-scope="scope">
          <el-button
            type="danger"
            icon="delete"
            @click="removeBackupFile(scope.$index,scope.row)"
          >删除</el-button>
          <el-button
            type="danger"
            icon="delete"
            @click="download(scope.row.attatchname)"
          >查看图片</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add, edit } from "@/api/tEquipment";
import { getDictDetails, dictDetailAdd } from "@/api/dictDetail";
import { getAllEqptType } from "@/api/tEqpttype";
import { uploadFile } from "@/api/upload";
import { getToken } from "@/utils/auth";
import { parseTime } from '@/utils/index'
import request from '@/utils/request'
import {
  getAttatchment,
  getAttatchFile,
  delAttatchment
} from "@/api/tAttachment";
import { log } from "util";
export default {
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    sup_this: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      dialog: false,
      eqptstatelist: [],
      eqptSystemList: [],
      eqptTypeList: [],
      eqptbrandlist: [],
      eqptmodelnamelist: [],
      enabledUploadBtn: true,
      // baseUrl: "blob:http://localhost:8013/",
      baseUrl: "blob:http://localhost:8000/api/tAttachmentFile?fileName=",
      fileList: [],
      form: {
        id: "",
        eqptsystem: "",
        eqpttypeid: "",
        eqptcode: "",
        eqptname: "",
        brandname: "",
        modelname: "",
        serialno: "",
        location: "",
        header: "",
        headerphone: "",
        manufacturer: "",
        purtime: "",
        supplier: "",
        suppliercontact: "",
        suppliercontactphone: "",
        warrantytime: "",
        eqptdesc: "",
        eqptstate: ""
      },
      rules: {
        eqptsystem: [
          { required: true, message: "请选择所属系统", trigger: "blur" }
        ],
        eqpttypeid: [
          { required: true, message: "请选择设备类型", trigger: "blur" }
        ],
        serialno: [
          { required: true, message: "请输入序列号", trigger: "blur" }
        ],
        location: [
          { required: true, message: "请输入安装位置", trigger: "blur" }
        ],
        warrantytime: [
          { required: true, message: "请输入质保期限", trigger: "blur" }
        ]
      },
      headers: {
        Authorization: "Bearer " + getToken()
        //token为系统访问需要的,放在header中
      }
    };
  },
  created() {
    const explorer = navigator.userAgent;
    if (explorer.indexOf("Chrome") >= 0) {
      this.style = "width: 200px";
    } else {
      this.style = "width: 172px";
    }
    // dialogVisibleImage = false;
  },
  methods: {
    onSubmitBrand() {
      var data = {
        id: "",
        label: this.form.brandname,
        value: this.form.brandname,
        sort: 999,
        dict: { id: 14 }
      };
      dictDetailAdd(data)
        .then(res => {
          this.$notify({
            title: "添加成功",
            type: "success",
            duration: 2500
          });
        })
        .catch(err => {
          this.loading = false;
          console.log(err.response.data.message);
        });
    },
    onSubmitModelname() {
      var data = {
        id: "",
        label: this.form.modelname,
        value: this.form.modelname,
        sort: 999,
        dict: { id: 15 }
      };
      dictDetailAdd(data)
        .then(res => {
          this.$notify({
            title: "添加成功",
            type: "success",
            duration: 2500
          });
        })
        .catch(err => {
          this.loading = false;
          console.log(err.response.data.message);
        });
    },
    cancel() {
      this.resetForm();
    },
    doSubmit() {
      this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.isAdd) {
              this.doAdd();
            } else this.doEdit();
        }
      });
    },
    doAdd() {
      add(this.form)
        .then(res => {
          this.resetForm();
          this.$notify({
            title: "添加成功",
            type: "success",
            duration: 2500
          });
          this.loading = false;
          this.$parent.$parent.init();
        })
        .catch(err => {
          this.loading = false;
          console.log(err.response.data.message);
        });
    },
    doEdit() {
      this.form.purtime = parseTime(this.form.purtime)
      edit(this.form)
        .then(res => {
          this.resetForm();
          this.$notify({
            title: "修改成功",
            type: "success",
            duration: 2500
          });
          this.loading = false;
          this.sup_this.init();
        })
        .catch(err => {
          this.loading = false;
          console.log(err.response.data.message);
        });
    },
    resetForm() {
      this.dialog = false;
      this.$refs["form"].resetFields();
      this.eqptstate = null;
      this.form = {
        id: "",
        eqptsystem: "",
        eqpttypeid: "",
        eqptcode: "",
        eqptname: "",
        brandname: "",
        modelname: "",
        serialno: "",
        location: "",
        header: "",
        headerphone: "",
        manufacturer: "",
        purtime: "",
        supplier: "",
        suppliercontact: "",
        suppliercontactphone: "",
        warrantytime: "",
        eqptdesc: "",
        eqptstate: ""
      };
    },
    getEqptStates() {
      getDictDetails("eqpt_status").then(res => {
        this.eqptstatelist = res.content;
      });
    },
    getEqptBrand() {
      getDictDetails("eqpt_brand").then(res => {
        this.eqptbrandlist = res.content;
      });
    },
    getEqptModelname() {
      getDictDetails("eqpt_modelname").then(res => {
        this.eqptmodelnamelist = res.content;
      });
    },
    getEqptSystem() {
      getDictDetails("eqpt_system").then(res => {
        this.eqptSystemList = res.content;
      });
    },
    getEqptType(systemid) {
      // this.form.eqpttypeid = null;
      getAllEqptType(systemid)
        .then(res => {
          this.eqptTypeList = res.content;
        })
        .catch(err => {
          console.log(err.response.data.message);
        });
    },
    selectFun() {
      console.log(this.form.eqptsystem);
      this.getEqptType(this.form.eqptsystem);
    },
    onSuccess(response, file, fileList) {
      this.enabledUploadBtn = true;
      this.uploadBtnIcon = "el-icon-upload2";
      this.btnText = "数据导入";
      this.getAllAttatchment(this.form.eqptcode);
    },
    onError(err, file, fileList) {
      this.enabledUploadBtn = true;
      this.uploadBtnIcon = "el-icon-upload2";
      this.btnText = "数据导入";
    },
    beforeUpload(file) {
      this.enabledUploadBtn = false;
      this.uploadBtnIcon = "el-icon-loading";
      this.btnText = "正在导入";
    },
    uploadFile() {
      return "";
    },
    getAllAttatchment(fileKey) {
      getAttatchment(fileKey).then(res => {
        this.fileList = res.content;
      });
    },
    download: function(fileName) {
      // return "/api/download?fileName="+fileName;
      getAttatchFile(fileName)
      .then(res => {
          //
        })
        .catch(err => {
          console.log(err.response.data.message);
        });
    },
    handleLoadError(e){
        const img = e.srcElement;
        // img.onerror = null;
    },
    uploadUrl() {
      return (
        "http://localhost:8000/api/tAttachmentNew?eqptcode=" +
        this.form.eqptcode
      );
    },
    removeBackupFile(index, row) {
      let _vue = this;
      this.$confirm("确定删除此文件?", "提示", {
        confirmButtonText: "确定",
        showCancelButton: true,
        type: "warning"
      }).then(() => {
        delAttatchment(row.id).then(res => {
          _vue.$message.success("删除成功");
          this.getAllAttatchment(this.form.eqptcode);
        });
      });
    },
    querySearch(queryString, cb) {
      //this.getCustomers(queryString);
      const params = {
        customerName:queryString
      }
      request({
        url: 'api/tCustomerInfo',
        method: 'get',
        params
      }).then(res => {
       this.faultDevices = []
       this.devices = []
       this.customers = []
       const content = [].concat(res.content);
       const _this = this
       content.forEach(function(data, index) {
          const customer = { id: data.id,value: data.customerName,address:data.address}
          _this.customers.push(customer)
        })
        cb(this.customers);
      }).catch(err => {
        console.log(err.response.data.message)
      }) 
    },
    handleSelect(item) {
      this.form.customerId = item.id
    },
  }
};
</script>

<style scoped>
</style>
